<?php

namespace helper;

class StringHelper
{
    /**
     * @param $str
     * @return mixed
     *
     * 把下画线转成驼峰命名法
     */
    public static function convertUnderline($str)
    {
        $str = preg_replace_callback('/([-_]+([a-z]{1}))/i', function ($matches) {
            return strtoupper($matches[2]);
        }, $str);
        return $str;
    }


    /**
     * @param $str
     * @return string
     *
     * 把驼峰命名法转成下画线
     */
    public static function camelize($str)
    {
        $dstr = preg_replace_callback('/([A-Z]+)/', function ($matchs) {
            return '_' . strtolower($matchs[0]);
        }, $str);
        return trim(preg_replace('/_{2,}/', '_', $dstr), '_');
    }


    public static function uuid()
    {
        $uuid = \Faker\Provider\Uuid::uuid();
        $uuid = str_replace("-", "", strtoupper($uuid));
        return $uuid;
    }


    public static function json($state = 200, $info = "操作成功", $data = [])
    {
        return json_encode(["state" => $state, "info" => $info, "data" => $data], JSON_UNESCAPED_UNICODE);
    }

    public static function data2json($data, $message = '操作成功', $code = 200)
    {
        return json_encode([
            "code" => $code,
            "message" => $message,
            "data" => $data
        ], JSON_UNESCAPED_UNICODE);
    }

    public static function deJson($json, $array = true)
    {
        return json_decode($json, $array);
    }


    //将数组转成xml
    public static function json2XML($source)
    {
        $string = "";
        foreach ($source as $k => $v) {
            if (is_numeric($k)) {
                continue;
            }
            $string .= "<" . $k . ">";
            //判断是否是数组，或者，对像
            if (is_array($v) || is_object($v)) {
                //是数组或者对像就的递归调用
                $string .= self::json2XML($v);
            } else {
                //取得标签数据
                $string .= $v;
            }
            $string .= "</" . $k . ">";
        }
        return $string;
    }

}
